gpt4 book ai didi

C++ - 类中的私有(private)变量

转载 作者:可可西里 更新时间:2023-11-01 16:26:21 25 4
gpt4 key购买 nike

我正在尝试使用私有(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

在 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 中构建时,它说:

  • ...\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”未在此范围内声明

但是当我运行它(而不是构建它)时,一切正常。

最佳答案

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

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

void TestClass::print(int x)
//^^^^^^^^^^^this

这是必要的,以便编译器可以知道setprint 是类TestClass 的成员函数。一旦你编写它,使它们成为成员函数,它们就可以访问类的私有(private)成员。

此外,如果没有 TestClass::setprint 函数将成为自由函数。

关于C++ - 类中的私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5613143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com