【问题标题】:Why this method code doesn't take integer as it's parameter [duplicate]为什么此方法代码不将整数作为参数[重复]
【发布时间】:2016-08-27 07:54:51
【问题描述】:

我只是想设计一个类来设置和获取 C++ 学生的详细信息。 因此,为了设置学生的详细信息,我调用了set_data(name,roll) 方法。但是这个编译错误即将到来。我已按预期将与实际参数相同的数据类型传递给函数。我不明白为什么会出现错误。

G:\>g++ 5.cpp
5.cpp: In function 'int main()'
5.cpp:26:23: warning: deprecate
rite-strings]
 obj.set_data("asdf",15);

代码是---

#include<iostream>
using namespace std;
#include<string.h>
#include<stdlib.h>      
class pntr_obj
{
char *name;
int roll;
public:
void set_data(char *name,int roll)
{
this->name=name;
this->roll=roll;
}
void print()
{
cout<<"name is "<<this->name<<endl;

cout<<"roll is "<<this->roll<<endl;
}
};
int main()
{
pntr_obj obj;

obj.set_data("asdf",15);
obj.print();
return 0;
}

【问题讨论】:

  • 缩进你的代码,please
  • 您了解字符串文字 ("asdf") 的 type 是什么了吗?
  • 将 *char 更改为字符串。
  • "asdf" 被当作一个字符串,如果我错了,请纠正我
  • 下一次,请在发布新问题之前搜索您收到的错误消息/警告。这很容易找到。

标签: c++


【解决方案1】:

我已按预期将与实际参数相同的数据类型传递给函数。

没有。 "asdf"string literal 类型为 const char[5],它可能会衰减到 const char*,但不会衰减到 char *

在 C 中,字符串文字的类型为 char[],并且可以直接分配给(非常量)char*。 C++03 也允许它(但不推荐使用它,因为文字在 C++ 中是 const )。 C++11 不再允许在没有强制转换的情况下进行此类分配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-08
    • 2020-04-05
    • 2015-02-17
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    相关资源
    最近更新 更多