C++/Win32 构造函数不使用从对话框获取的字符串初始化变量

C++/Win32 constructor not initializing variable with string obtained from dialog

本文关键字:获取 对话框 字符串 变量 初始化 Win32 构造函数 C++      更新时间:2023-10-16

我正在尝试使用从对话框中获得的 std::string 创建一个对象,调试时我看到它已成功获取并传递给构造函数,但是本地参数保留为 "。

这是我的类标题:

#pragma once
#include <iostream>
#include <istream>
#include <fstream>
#include <string>
class Motorcycle
{
public:
Motorcycle();
Motorcycle(const std::string& nameP, int mileage) : name(nameP), mileage(mileage) {};
friend std::ostream & operator << (std::ostream & out, const Motorcycle & obj)
{
out << obj.name << "n" << obj.mileage << std::endl;
return out;
};
//friend std::istream & operator >> (std::istream & in, const Motorcycle & obj)
//{
//  in >> &obj.name[0] >> obj.mileage;
//  return in;
//};
private:
std::string name;
int mileage;
};

cpp 仍然是空的(我想也许我应该把构造函数放在那里,但结果是一样的?

#include "stdafx.h"
#include "Motorcycle.h"
#include <string>
Motorcycle::Motorcycle()
{
}
//Motorcycle::Motorcycle(const std::string &nameP, int mileage) : name(nameP), mileage(mileage) {};

这是对话框和其他函数的过程:

BOOL CALLBACK CreateBikeProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
std::string name = "";
int mileage;
switch (message)
{
case WM_INITDIALOG:
return TRUE;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
GetDlgItemTextA(hWnd, IDC_EDIT_NAME, &name[0], 16);
mileage = GetDlgItemInt(hWnd, IDC_EDIT_MILEAGE, NULL, FALSE);
if (ValidateBike(name, mileage))
{
CreateBike(name, mileage);
EndDialog(hWnd, IDOK);
}
break;
case IDCANCEL:
EndDialog(hWnd, IDCANCEL);
break;
}
break;
default:
return FALSE;
}
return TRUE;
}
BOOL ValidateBike(std::string& name, int mileage)
{
if (name[0] == ' ' || name.find_first_not_of(' ') != name.npos
|| mileage < 1)
return false;

return true; 
}
BOOL CreateBike(std::string& name, int mileage)
{
Motorcycle bike = Motorcycle(name, mileage);

std::ofstream ofs("motorcycles.txt", std::ios::app);
ofs << bike;
ofs.close();
return true;
}

我可以看到 CreateBikeProc 中的名称被分配并传递给其他函数,但随后 bike.name 为空......

此外,friend std::istream & operator >>被注释掉,因为它会导致另一个错误......Error 1 error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion)

提前感谢...

问题就在这里:

GetDlgItemTextA(hWnd, IDC_EDIT_NAME, &name[0], 16);

不能将值读入这样的字符串。需要创建一个缓冲区,然后从缓冲区更新字符串:

char buffer[17]="";
GetDlgItemTextA(hWnd, IDC_EDIT_NAME, &buffer, 16);
name=buffer;

对于operator>>,您有两个问题:第一个是const Motorcycle参数,第二个是您尝试就地覆盖字符串。这是一个固定版本:

friend std::istream & operator >> (std::istream & in, Motorcycle & obj)
{
in >> obj.name >> obj.mileage;
return in;
};