c++ - 不能创建一个类的多个实例?
问题描述
我的问题是我想为不同的升级创建升级类的多个实例。也许是因为我习惯了 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;
源.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;
};
这将为name
每个Source
. 我建议您研究一下类字段以及它们之间的差异public
和private
访问权限。
推荐阅读
- sql-server-2014 - SQL 数据库图 - SQL Server 2014?
- amazon-web-services - 在 Cognito 内置登录页面中显示用户名以外的其他内容
- javascript - 为什么 XMLHTTP 请求不适用于我的服务器?
- django - 如何使用 Django 将自定义对象传递给表单
- python - 如何更改 Odoo 10 中模型的默认搜索字段?
- javascript - 图形的随机颜色。帆布。javascript
- reactjs - 使用 redux-thunk 捕获错误
- bash - Bash 将多行文件转换为 n 列 CSV
- youtube-api - 关于从服务器或客户端使用 YouTube 数据 API 的困惑
- android - androidTest 包中 ndk-stack 的 obj 文件在哪里