首页 > 解决方案 > 有一个参数字符串问题的构造函数

问题描述

首先,我不是一个经验丰富的 C++ 程序员,我只是想通过我的面向对象编程考试。我知道如果我有一个只有一个参数的类构造函数,如果我做这样的事情 -> myClass object = something就像传递something给带有一个参数的构造函数,对吧?那么,为什么这可以正常工作:

#include <iostream>
using namespace std;

class A
{
public:
    int m;

    A(int M){
        m = M;
    }

    print(){
        cout << "m: " << m << "\n";
    }
};

int main()
{
    A x = 132;
    x.print();

return 0;
}

这不会:

#include <iostream>
using namespace std;

class A
{
public:
    string m;

    A(string M){
        m = M;
    }

    print(){
        cout << "m: " << m << "\n";
    }
};

int main()
{
    A x = "RANDOMSTRING";
    x.print();

return 0;
}

我在第二种情况下得到的错误是: error: conversion from 'const char [13]' to non-scalar type 'A' requested

我想这是该字符串参数的某种问题,但是为什么呢?

标签: c++stringconstructor

解决方案


推荐阅读