我试着打印数组到屏幕上。不幸的是,它打印了4行空白行。
// CarWarhouse.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <string>
#include <iostream>
#include "agents.h"
using namespace std;
int main()
{
string agentName;
int agentID;
agents A_1;
cout << "Administrative login: ";
cin >> agentName;
A_1.setAgentName(agentName);
cout << "Administrative password: ";
cin >> agentID;
while (agentID != A_1.getAgentID())
{
cout << "Invalid login\n";
cout << "\nAdministrative password: ";
cin >> agentID;
}
cout << endl << "Welcome back, Agent " << endl;
cout << "Active Agents: " << endl;
A_1.agentIdentities(); //Function call to agents.cpp
}
agents.cpp
#include "pch.h"
#include "agents.h"
#include <string>
agents::agents() {
agentName = "";
agentID = 1111;
int const size = 4;
string agentMembers[size] = { "Jacob", "Nathan", "Tomas", "Jack" }; //Agent members string array I want to print to screen.
}
agents::agents(string name, int ID)
{
agentName = name;
agentID = ID;
}
agents::~agents()
{}
string agents::getAgentName() const
{
return agentName;
}
int agents::getAgentID() const
{
return agentID;
}
void agents::setAgentName(string incoming)
{
agentName = incoming;
}
void agents::setAgentIdentity(int ID)
{
agentID = ID;
}
void agents::agentIdentities() //Main calls this function.
{
for (int i = 0; i < size; i++)
{
cout << agentMembers[i] << endl;
}
cout << agentMembers[0];
}
#pragma once
#include <iostream>
#include <string>
using namespace std;
#ifndef agents_h
#define agents_h
class agents{
public:
//First thing, default constructor
agents();
//Overload Constructor
agents(string, int);
//Destructor
~agents();
//Accessor Functions
//If accessor doesn't modify member variables, end with const on the function name.
string getAgentName() const;
//getName returns name of the customer.
int getAgentID() const;
void setAgentName(string);
//getName returns the newly assigned customer reference number.
void setAgentIdentity(int);
void agentIdentities();
//Retrieves agent identites (names within the string array).
private:
//Member variables
string agentName;
int agentID;
string agentMembers[4];
int size = 4;
};
#endif我已经在代码中确定了关键感兴趣的三个领域。我尝试使用从main到agents.cpp的函数调用从main打印字符串数组。
每次我运行这段代码时,它都会打印4行空白行,我对c++相当陌生,因为这是我在大学的第四个星期。
谢谢。
发布于 2019-02-20 10:42:03
这是错误(非常常见的新手错误)。
agents::agents() {
agentName = "";
agentID = 1111;
int const size = 4;
string agentMembers[size] = { "Jacob", "Nathan", "Tomas", "Jack" };
}它应该是
agents::agents() {
agentName = "";
agentID = 1111;
size = 4;
agentMembers = { "Jacob", "Nathan", "Tomas", "Jack" };
}您的代码声明了名为size和agentMembers的新变量,它们与类中声明的变量完全无关(除了具有相同的名称)。这就是为什么构造函数不更新类变量的原因,因为所设置的只是一些局部变量,一旦构造函数退出,这些局部变量就不再存在。
但是,由于我们在构造函数的顶部,因此值得指出的是,初始化类变量的最佳方法是使用initialiser列表
agents::agents() : agentName(""), agentID(1111), size(4),
agentMembers{ "Jacob", "Nathan", "Tomas", "Jack"} {
}这个版本用给定的值初始化类变量,您的版本有两个步骤,首先默认初始化类变量,然后将给定的值分配给变量。这是低效率和没有理由不喜欢初始化列表版本。
https://stackoverflow.com/questions/54784150
复制相似问题