【问题标题】:Where did i go wrong c++ classes [closed]我在哪里出错了 C++ 类 [关闭]
【发布时间】:2022-01-09 14:41:27
【问题描述】:

您好,这是我在堆栈溢出时的第一个主题(问题),我在 Code::Blocks 尝试了一个关于 c++ 类的项目,但出了点问题

#include <iostream>
using namespace std;

class char1
{
    public:
    string charName;
    float charLength;

    void printName()
    {
        cout<<"char name is"<<charName;
    }
};

int main()
{
    int charNAME;
    float charLENGTH;

    cout<<"write your char's name"<<endl;
    cin>>charNAME;

    cout<<"write your char's length"<<endl;
    cin>>charLENGTH;

    char1 name;
    char1 length;

    name.charName=charNAME;
    length.charLength=charLENGTH;

    return 0;
}

当我运行程序时,它问我 char 的名字我写了一些东西,在它询问 char 的长度之后 但是程序到此为止我什么都做不了 here is picture for help

【问题讨论】:

  • 您要创建一个char1,例如char1 my_char;。然后你想做my_char.charName = charName; mychar.charLength = charLength。至此程序完成并存在。
  • 是不是因为您将 charNAME 定义为 int 而不是 string?
  • 请不要使用“using namespace std;”。如果您需要一些来自 0...n 而不是 float 的值,请使用 unsigned int。请使用构造函数来初始化对象,而不是直接访问内部。如果我们只能有文字,请不要发布图片。 “但出了点问题”也不是一个好的错误描述。你有编程或 C++ 的初学者书籍吗?阅读第一页的好时机,尤其是为什么我们想要类而不是全局变量。
  • @RobinDillen 我写的是 charLENGTH 而不是 charLength 是程序认为其中两个相同吗?
  • @Klaus 我说我是新手,对此我很抱歉,而且我还有一本关于 c++ 的初学者书籍

标签: c++ class


【解决方案1】:

对您的代码进行了一些修复,以向您展示如何在实践中使用您的类(包括一些 c++ 编码技巧)。

#include <string>
#include <iostream>

// using namespace std; <== don't do this 
// https://*.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

//class char1
class Character // <== give classes clear names, makes code more readable
{
public:
    std::string name;
    float length;

    // I understand you want to do this to test stuff.
    // but from a design point of view printing is not something
    // a character can do to himself 
    /*
    void printName()
    {
        cout << "char name is" << charName;
    }
    */
};

// bit offtopic but : 
// if you want to add support for printing your character
// its more common to overload operator<< for streams like this
std::ostream& operator<<(std::ostream& os, const Character& character)
{
    os << "Your character's name = " << character.name << ", and his/her length = " << character.length << "\n";
    return os;
}


int main()
{
    // int charNAME; in your class this is a string, be consistent.
    // float charLENGTH;

    // make an instance of the Character class
    Character character;

    std::cout << "Enter your char's name : "; // << endl; avoid using endl use "\n" if you want a newline
    std::cin >> character.name;

    std::cout << "Enter your char's length : "; // << endl;
    std::cin >> character.length;

    std::cout << "\n";
    std::cout << character; // this will now call your overloaded << operator 
    
    return 0;
}

【讨论】:

  • 感谢您的回答,它很有用,我会尽量不使用“使用命名空间”