嘿伙计,所以我在我的c ++程序中遇到了我的析构函数问题.当我运行程序并接受用户输入时,它突然调用析构函数,然后cout甚至可以在语句中打印.假设用户输入将是一个,因为我设计了这部分代码只接受输入1.我认为析构函数在你离开范围时被调用所以我认为析构函数应该在cout之后被调用至少我将在下面评论的if语句,让你们更容易阅读.如果有人可以解释我的错误并纠正它会很棒!在我的头文件中我有
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
class creature{
public:
creature();//default constructor
creature(int a);
~creature();//desconstructor
string getName();//accessor for the name
static int getNumObjects();
private:
string name;
int happy_level;
static int count;
};
Run Code Online (Sandbox Code Playgroud)
在我的实现文件中,我有
#include "creature.h"
int creature::count=0;//initialize static member variable
creature::creature(){//default constructor
name="bob";
++numberobject;
cout<<"The default constructor is being called"<<endl;
}
creature::creature(int a)
{
if(a==1)
{
name="billybob";
}
else if(a==2)
{
name="bobbilly";
}
else if(a==3)
{
name="bobbertyo";
happy_level=1;
}
}
creature::~creature()
{
cout<<"The destructor …Run Code Online (Sandbox Code Playgroud) 嘿,所以我很难搞清楚代码来计算独特单词的数量.我在psudeocode方面的思考过程是先制作一个矢量,vector<string> unique_word_list;然后我会让程序读取每一行,所以我会有类似的东西while(getline(fin,line)).对我来说困难的部分是提出代码,我检查向量(数组)以查看字符串是否已经存在.如果它在那里我只是增加字数(足够简单)但如果它不在那里那么我只是向矢量添加一个新元素.如果有人能帮助我,我真的很感激.我觉得这并不难,但由于某种原因,我无法想到将字符串与数组内部的数据进行比较并确定它是否是唯一的单词的代码.
错误说没有匹配的函数要求push_back().
我包括<vector>所以我不明白为什么会发生这种错误.如果你还可以告诉我如何接受一个字符串并将其存储到一个非常有用的矢量中!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> list;
char input;
while(cin>>input)
{
list.push_back(input);
}
for(int i=0;list.size();i--)
{
cout<<list[99-i];
}
}
Run Code Online (Sandbox Code Playgroud) 嘿伙计,所以我正在研究一个基本程序,需要我们练习构造函数,但我不明白为什么我得到错误的输出.每当我运行代码时,我总是把bob作为我的输出而不是其他的bob.如果有人能告诉我我做错了什么以及如何解决它会很棒!
以下是我的.h文件:
#include <iostream>
#include <string>
using namespace std;
class creature{
public:
creature();
creature(int a);//initalizes the name of the creature based on what the user chooses(1,2, or 3 determines the monster name)
string getName();//accessor for the name
string getColor();//accessor for the color
private:
string name;
string color;
};
Run Code Online (Sandbox Code Playgroud)
以下是我的一个cpp文件:
creature::creature(){
name="bob";
color="black";
}
creature::creature(int a)
{
if(a==1)
name="bob_1";
else if(a==2)
name="bob_2";
else if(a==3)
name="bob_3";
}
string creature::getName()
{
return name;
}
Run Code Online (Sandbox Code Playgroud)
以下是我的一个cpp文件:
#include "creature.h"
int main()
{
creature monster;
int …Run Code Online (Sandbox Code Playgroud)