gpt4 book ai didi

c++ - 表达式必须是可修改的指向字符的左值指针参数

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:33 25 4
gpt4 key购买 nike

这是完整的代码。编译后出现以下错误:

error LNK2019: unresolved external symbol "void __cdecl CandyBarFunc(struct CandyBar &,char const *,double,int)" (?CandyBarFunc@@YAXAAUCandyBar@@PBDNH@Z) referenced in function _wmain

fatal error LNK1120: 1 unresolved externals

#include "stdafx.h"
#include <iostream>
using namespace std;

struct CandyBar
{
char name[40];
double weight;
int calories;
};

void CandyBarFunc(CandyBar & astruct, const char * aname = "Millennium Munch", double aweight = 2.85, int acalories = 350);
void CandyBarFunc(const CandyBar & astruct);

int _tmain(int argc, _TCHAR* argv[])
{
CandyBar MyCandyBar;
CandyBarFunc(MyCandyBar, "Hello World Candy Bar", 1.25, 200);
CandyBarFunc(MyCandyBar);
return 0;
}

void CandyBarFunc(CandyBar & astruct, char * aname, double aweight, int acalories)
{
strncpy(astruct.name,aname,40);
astruct.weight = aweight;
astruct.calories = acalories;
}

void CandyBarFunc(const CandyBar & astruct)
{
cout << "Name: " << astruct.name << endl;
cout << "Weight: " << astruct.weight << endl;
cout << "Calories: " << astruct.calories;
}

最佳答案

因为 name 被定义为 char name[40],你不能写试图改变地址的 astruct.name = aname name 数组。但是不能更改数组的地址。因此错误。

这样做:strcpy(astruct.name, aname);

更好的是,将 CandyBar 定义为,

struct CandyBar
{
std::string name;
double weight;
int calories;
};

现在你可以写:astruct.name = aname;

关于c++ - 表达式必须是可修改的指向字符的左值指针参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5006583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com