无法创建一个类的多个实例
Cannot create multiple instances of a class?
我的问题是,我想为不同的升级创建升级类的多个实例。也许是因为我习惯了java,但我不能只键入Source first("first"), second("second");
,因为如果我这样做并调用first.getName()
,例如,我会得到"second"
。我做了一个示例文件,我只写了我正在努力解决的问题,所以你不必试图理解我混乱的代码。
Source.cpp:我想要这个类的多个实例。
#include "Source.h"
std::string name;
Source::Source()
{
}
Source::Source(std::string nameToSet)
{
name = nameToSet;
}
std::string Source::getName()
{
return name;
Source.h
#pragma once
#include <string>
class Source {
public:
Source();
Source(std::string namel);
std::string getName();
};
测试.cpp
#include "Source.h"
#include "iostream"
Source first("first"), second("second");
int main()
{
std::cout << first.getName() << std::endl;
}
输出:秒
测试.h
#pragma once
#include <string>
问题出在这行:
std::string name;
这声明了一个名为name
的全局字符串。此变量未与任何Source
实例关联。相反,您需要在Source
类中声明一个字段:
class Source {
public:
Source();
Source(std::string namel);
std::string getName();
// Add these two lines
private:
std::string name;
};
这将为每个Source
提供一个name
。我建议您研究类字段以及public
和private
访问之间的差异。
在头文件中添加std::string名称,如下所示:
#pragma once
#include <string>
class Source {
private:
std::string name;
public:
Source();
Source(std::string namel);
std::string getName();
};
这样,每次调用构造函数时,"name"都会被初始化为一个值,该值引用您的特定实例(第一个、第二个等(。
相关文章:
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 如何将模板的实例传递给另一个模板的另一个实例?
- 如何在另一个类中创建类的实例?
- 如果模板参数是另一个模板的实例化,则键入特征测试
- 重载运算符*以获取对另一个类的实例的引用
- 我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
- 如何正确实例化静态字段 tat 是另一个类对象
- 创建子类的多个实例,其中只有一个超类实例
- C++ - 使用另一个类的构造函数实例化一个对象
- 如何使用另一个模板化类的实例模板化类?
- 在类的第一个/最后一个实例存在之前/之后调用一对函数.有没有更好的方法?
- 在另一个类中创建类实例时出现问题
- C++:递归地将字符串中一个字母的所有实例替换为另一个字母
- 我想知道我是否可以将一个类分配给特定的成员数据并创建该类的实例
- 如何使用其中一个具体类实例化抽象类?
- 传递一个可能更改为类实例的可调用函数
- 无法创建一个类的多个实例
- 有什么方法可以部分实例一个C 模板