这段代码的基础是在一个教程中找到的,所以我不太清楚它为什么要这样做。
错误:
main.cpp: In function ‘int main()’:
main.cpp:8:32: error: cannot call member function ‘int TestC::getAnswer()’ without object
std::cout << TestC::getAnswer() << std::endl;main.cpp
#include <iostream>
#include "TestC.hpp"
int main()
{
TestC(1, 1);
std::cout << TestC::getAnswer() << std::endl;
return 0;
}TestC.cpp
#include "TestC.hpp"
TestC::TestC(int x, int y)
{
gx = x;
gy = y;
}
int TestC::getSum()
{
return gx + gy;
}TestC.hpp
#ifndef TestC_H
#define TestC_H
class TestC
{
int gx;
int gy;
public:
TestC(int x, int y);
int getAnswer();
};
#endif我是这样编制的:
g++ main.cpp -o Main发布于 2014-09-22 17:44:48
您不是通过调用构造函数来创建对象的。你必须真正声明一个对象
TestC myC{1, 1};
int answer = myC.getAnswer();因此,您的main函数将更改为
int main()
{
TestC myC{1, 1};
std::cout << myC.getAnswer() << std::endl;
return 0;
}https://stackoverflow.com/questions/25980059
复制相似问题