字符串作为 C++ 构造函数中的参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8546869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:46:01  来源:igfitidea点击:

String as a parameter in a constructor in C++

c++stringparametersconstructor

提问by System

class example {
 private:
    char Name[100];        
 public:

     example(){strcpy(Name, "no_name_yet");}
     example(char n[100]){strcpy(Name, n);}


   };



int main() {
     example ex;
     char n[100];

     cout<<"Give name ";
     cin>>n;
      example();
  }

I want to use the constructor with the parameter so that when the user gives a name it gets copied to the name variable. How can I use the constructoe with the parameter instead of the default one? I tried

我想将构造函数与参数一起使用,以便在用户提供名称时将其复制到 name 变量中。如何使用带有参数的构造函数而不是默认的构造函数?我试过

  example(n)
example(char n)
  example(*n)
   example(n[100])

but none of them work...

但他们都没有工作......

回答by dasblinkenlight

It is example my_instance_of_example(n).

它是example my_instance_of_example(n)

I must note, however, that using char arrays for strings is not what you do in C++. You should use std::stringinstead, it gives you a lot more flexibility.

但是,我必须注意,对字符串使用 char 数组并不是您在 C++ 中所做的。您应该改用std::string它,它为您提供了更大的灵活性。

回答by Xeo

Easy:

简单:

#include <string>
#include <iostream>

class example {
 private:
    std::string name;

 public:
    example() : name("no name yet"){}
    example(std::string const& n) : name(n){}
};


int main() {
     example ex;
     std::string n;

     std::cout << "Give name ";
     std::cin >> n;
     example ex(n); // you have to give your instance a name, "ex" here
                    // and actually pass the contructor parameter
}