该代码的基础在教程中找到,所以我不太确定它为什么这样做。类/头文件 - 无法在没有对象的情况下调用成员
错误:
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
为了'TESTC ::的getAnswer()'工作,'的getAnswer()'将有成为“TestC”类的“静态”成员。 – Andro 2014-09-22 17:45:30
所以我把'int getAnswer();'改成'static int getAnswer();'但它仍然不起作用。它只是为TestC :: TestC()和TestC :: getAnswer()提供了类似的错误,用于未定义的引用。 – Nathan 2014-09-22 17:50:43
看完这个,你应该明白,应该看看事情是怎么样的。 http://www.learncpp.com/cpp-tutorial/812-static-member-functions/ – Andro 2014-09-22 17:54:54