C++ - 类中的私有变量

Mr.*_*ums 9 c++ private class

我试图在私有变量的单独文件中创建一个类.到目前为止,我的类代码是:

在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
Run Code Online (Sandbox Code Playgroud)

在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;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试构建Code :: Blocks时,它说:

  • ...\TestClass.cpp:在函数'void set(std :: string)'中:
  • ...\TestClass.cpp:12:错误:'hi'未在此范围内声明
  • ...\TestClass.cpp:在函数'void print(int)'中:
  • ...\TestClass.cpp:17:错误:'hi'未在此范围内声明
  • ...\TestClass.cpp:19:错误:'hi'未在此范围内声明
  • ...\TestClass.cpp:21:错误:'hi'未在此范围内声明
  • ...\TestClass.cpp:23:错误:'hi'未在此范围内声明

但是当我运行它(并且不构建它)时,一切正常.

Naw*_*waz 18

你忘了写TestClass::,如下所示:

void TestClass::set(string x)
   //^^^^^^^^^^^this

void TestClass::print(int x)
   //^^^^^^^^^^^this
Run Code Online (Sandbox Code Playgroud)

这是必要的,以便编译器可以知道set并且print是类的成员函数TestClass.一旦你编写它,使它们成为成员函数,它们就可以访问类中的私有成员.

此外,没有识别TestClass ::,setprint功能将成为免费的功能.


wkl*_*wkl 2

您不使用类名来解析您的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;
}
Run Code Online (Sandbox Code Playgroud)