我试图在私有变量的单独文件中创建一个类.到目前为止,我的类代码是:
在TestClass.h中
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <string>
using namespace std;
class TestClass
{
    private:
        string hi;
    public:
        TestClass(string x);
        void set(string x);
        void print(int x);
};
#endif
在TestClass.cpp中
#include "TestClass.h"
#include <iostream>
#include <string>
using namespace std;
TestClass::TestClass(string x)
{
    cout << "constuct " << x << endl;
}
void set(string x){
    hi = x;
}
void print(int x){
    if(x == 2)
        cout << hi << " x = two\n";
    else if(x < -10)
        cout << hi << " x < -10\n";
    else if(x >= 10)
        cout << hi << " x >= 10\n";
    else
        cout << hi << " x = " << x << endl;
}
当我尝试构建Code :: Blocks时,它说:
但是当我运行它(并且不构建它)时,一切正常.
Naw*_*waz 18
你忘了写TestClass::,如下所示:
void TestClass::set(string x)
   //^^^^^^^^^^^this
void TestClass::print(int x)
   //^^^^^^^^^^^this
这是必要的,以便编译器可以知道set并且print是类的成员函数TestClass.一旦你编写它,使它们成为成员函数,它们就可以访问类中的私有成员.
此外,没有识别TestClass ::,set和print功能将成为免费的功能.
您不使用类名来解析您的print和函数的范围。set
void TestClass::set(string x){
    hi = x;
}
void TestClass::print(int x){
    if(x == 2)
        cout << hi << " x = two\n";
    else if(x < -10)
        cout << hi << " x < -10\n";
    else if(x >= 10)
        cout << hi << " x >= 10\n";
    else
        cout << hi << " x = " << x << endl;
}