簡體   English   中英

Cout不是打印字符串名稱(沒有錯誤顯示)

[英]Cout isnt printing string name(No errors are showing)

為什么此代碼不顯示名稱? 我在Animals構造函數類中定義了名稱,但是當我運行代碼時,它只會忽略該定義。

動物類:

#pragma once

#include <vector>
#include <string>

class Animals
{
private:

    std::string name;

    std::vector<int> disgust = {1,3,5};
    std::vector <int> sleepTime = { 1,3,5 };
    std::vector <int> childs = { 1,2,3 };
    std::vector<Animals> theAnimals;

    int disgustBar;
    int sleepBar;
    int animalTotal;

    bool reproduce;

public:
    Animals(std::string name);
    ~Animals();

    void feeding(int i);
    void sleeping(int i);
    void description();
};

Animals.cpp

#include "stdafx.h"
#include "Animals.h"
#include <iostream>

Animals::Animals(std::string name)
{
    disgustBar = 7;
    sleepBar = 7;
}

Animals::~Animals()
{
}

void Animals::feeding(int i)
{
    disgustBar += i;
    return;
}

void Animals::sleeping(int i)
{
    sleepBar += i;
    return;
}

void Animals::description()
{
    std::cout << "The animal name is " + name  << std::endl;
}

主要:

#include "stdafx.h"
#include "Animals.h"
#include <string>
#include <iostream>

int main()
{
    Animals a("Allahu");
    a.description();

    return 0;
}

(這是我的第一篇文章,對不起,如果我犯任何錯誤)

您只是忘了初始化name成員,請執行以下操作:

Animals::Animals(std::string name) 
     : name(name) // <- init name
{
    disgustBar = 7;
    sleepBar = 7;    
}

建議1:使用構造函數初始化列表初始化所有成員:

Animals::Animals(std::string name) 
     : name(name), disgustBar(7), sleepBar(7)
{}

相關: 構造函數初始化與賦值

關於標識符名稱的注釋:

   : name(name)
//     ^    ^
//     |    +---- Constructor argument
//     +--------- Class member

建議2:為避免混淆,我將為類成員使用其他屬性名稱 例如“ name_ ”(末尾加下划線)。

建議3:如@Biffen所述,啟用所有警告並且不要忽略警告。

使用g++ -Wall -Wextra編譯代碼g++ -Wall -Wextra顯示以下警告:

 Animals.cpp:7:1: warning: unused parameter 'name' [-Wunused-parameter] Animals::Animals(std::string name) ^ 

您的構造函數需要初始化數據成員name

Animals::Animals(std::string n){
    disgustBar = 7;
    sleepBar = 7;
    name = n;
    //---^
}

或者可以修改您的構造函數以初始化所有數據成員,如下所示:

Animals::Animals(std::string n)
   : disgustBar(7), sleepBar(7), name(n) 
{ // body of the constructor }

為了避免將來出現類似的問題,請在構造函數的主體中包含一個用於測試輸入有效性的函數(即,如果所有數據成員都初始化為合理的值)。


注意:如果要計算所有實例化Animals對象的數量,則最好將數據成員animalTotal聲明為static並在構造函數的主體中遞增(在析構函數的主體中遞減)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM